package com.putao.album.collection;

import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.loopj.android.http.RequestParams;
import com.putao.album.R;
import com.putao.album.base.BaseActivity;
import com.putao.album.collection.bean.CollectionItem;
import com.putao.album.eventbus.BasePostEvent;
import com.putao.album.photodetail.ActivityPhotoDetail;
import com.putao.album.util.ActivityHelper;
import com.putao.album.util.CommonUtils;
import com.putao.album.util.HttpRequestUtil;
import com.putao.album.util.Loger;
import com.putao.album.util.PuTaoConstants;
import com.putao.album.util.StringHelper;
import com.putao.album.widget.pullrefresh.PullToRefreshGridView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import de.greenrobot.event.EventBus;

/**
 * Created by chen on 15-5-5.
 * 精选(收藏)相册页面
 */
public class ActivityCollection extends BaseActivity {
    private TextView title_tv;
    private Button right_btn;
    private List<CollectionItem> mDatalist = new ArrayList<CollectionItem>();
    private CollectionAdapter mCollectionAdapter;
    private int nextPage = 1;
    private PullToRefreshGridView grid_view;
    private boolean mIsLastPage = false;
    private boolean mIsRefreshing = false;
    private LinearLayout none_view;

    @Override
    public int doGetContentViewId() {
        return R.layout.activity_collection;
    }

    @Override
    public void doInitSubViews(View view) {
        title_tv = (TextView) findViewById(R.id.title_tv);
        title_tv.setText(R.string.collection_title);
        right_btn = (Button) findViewById(R.id.right_btn);
        right_btn.setVisibility(View.INVISIBLE);

        none_view = (LinearLayout) findViewById(R.id.none_view);
        grid_view = (PullToRefreshGridView) findViewById(R.id.grid_view);

        addOnClickListener(R.id.back_btn);
    }

    @Override
    public void doInitData() {
        mCollectionAdapter = new CollectionAdapter(mContext, mDatalist);
        grid_view.setAdapter(mCollectionAdapter);
        grid_view.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ArrayList<String> ids = new ArrayList<String>();
                for (int i = 0; i < mDatalist.size(); i++) {
                    ids.add(mDatalist.get(i).getId());
                }
                Bundle bundle = new Bundle();
                bundle.putStringArrayList("ids", ids);
                bundle.putInt("position", position);
                ActivityHelper.startActivity(mActivity, ActivityPhotoDetail.class, bundle);
            }
        });

        EventBus.getDefault().register(this);
        doGetData();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back_btn:
                finish();
                break;
            default:
                break;
        }

    }
    public void onEvent(BasePostEvent event) {
        switch (event.eventCode) {
            case PuTaoConstants.EVENTBUS_PHOTO_DELETED:
                Bundle bundle = event.bundle;
                boolean deleteAll = bundle.getBoolean("deleteAll", false);
                forceUpdate();
                break;
            case PuTaoConstants.EVENTBUS_ADD_OR_REMOVE_COLLECTION:
                forceUpdate();
                break;
            default:
                break;
        }
    }
    private void forceUpdate() {
        mIsLastPage = false;
        mDatalist.clear();
        doGetData();
    }
    void doGetData() {
        if (mIsLastPage || mIsRefreshing) {
            grid_view.onRefreshComplete();
            return;
        }
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("page", "" + nextPage);
        params.put("baby_id", CommonUtils.getBabyId());
        HttpRequestUtil.doHttpGetRequest(mContext, PuTaoConstants.API_GET_CHOICENESS_PHOTOLIST, new RequestParams(HttpRequestUtil.buildHttpRequestParams(params)), new HttpRequestUtil.RequestResponseListener() {
            @Override
            public void success(int statuscode, String response) {
                if (!StringHelper.isEmpty(response)) {

                    if (HttpRequestUtil.getResponseCode(response).equals(HttpRequestUtil.ResponseCode.api_code_200)) {
                        doAnalyzeDataList(HttpRequestUtil.getResponseData(response));
                    } else {
                        showToast(HttpRequestUtil.getResponseErrorMsg(response));
                    }
                }
            }

            @Override
            public void failed(int statuscode, String response) {
                Loger.d("response:::" + response);
                showToast(response);
            }
        });
        mIsRefreshing = true;
    }


    /**
     * 解析返回的标签相册列表数据
     *
     * @param data
     */
    void doAnalyzeDataList(JSONObject data) {
        JSONArray list = data.optJSONArray("list");
        if (list != null) {
            for (int i = 0; i < list.length(); i++) {
                JSONObject o = null;
                try {
                    o = list.getJSONObject(i);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                if (o != null) {
                    String id = o.optString("id");
                    String photo = o.optString("photo");
                    int is_praise = o.optInt("is_praise");

                    CollectionItem item = new CollectionItem();
                    item.setId(id);
                    item.setPhoto(photo);
                    item.setIs_praise(is_praise);
                    mDatalist.add(item);
                }
            }
            if(mDatalist.size()>0){
                none_view.setVisibility(View.GONE);
            }else {
                none_view.setVisibility(View.VISIBLE);
            }
            mCollectionAdapter.notifyDataSetChanged();
        }
        nextPage = data.optInt("nextPage");
        grid_view.onRefreshComplete();
        mIsRefreshing = false;
        if (nextPage == -1||nextPage==0) {
            mIsLastPage = true;
        }
    }

}
